<?php
include_once 'dingwork/model/db/interface/Db.php';
class Db_Driver_Mysqli implements Db_Driver_interface{
	public static $_config = array();
	private  $_link = null;
	public static function getInsterface($config){
		if(is_array($config)){
			self::$_config = $config;
		}else{
			throw new MysqliDbException('数据库配置信息出错');
		}
		return new Db_Driver_Mysqli();
	}
	public function __construct(){
		$this->_link = new mysqli(self::$_config['DB_HOST'],self::$_config['DB_USER'],self::$_config['DB_PASSWORD'],self::$_config['DB_DBNAME'],self::$_config['DB_PORT']);
		if($this->_link->connect_errno > 0){
			throw new MysqliDbException('mysqli cann\'t connect!');
		}
		$this->_link->set_charset(self::$_config['DB_CHARSET']);
	}
	public function __destruct(){
		$this->_link->close();
	}
	public function getprefix(){
		return self::$_config['DB_PREFIX'];
	}
	public function getlink(){
		return $this->_link;
	}
	public function getQuery($table){
		$table = $this->getprefix().$table;
		return new DB_Mysqli_Crud($table,$this->_link);
	}
}
class DB_Mysqli_Crud implements DB_Crud_interface{
	protected $_table = null;
	protected $_link = null;
	protected $_map = array();
	protected $_sql = array();
	public function __construct($table,$link){
		$this->_table = $table;
		$this->_link = $link;
		$this->init();
	}
	private function init(){
		$this->_sql = array(
		'fields' => '*',
		'where' => 'where 1=1',
		'limit' => '',
		'orderby' =>'',
		'groupby' =>'',
		'join' =>'',
		'having' =>''
		);
	}
	protected function _ArraytoSqlStr($array){
		foreach($array as $k=>$v){
			$arr[] = '`'.$this->_table.'`.`'.$k.'`=\''.$this->_link->real_escape_string($v).'\'';
		}
		return $arr;
	}
	public function add($array){
		if(!empty($array)){
			$arr = $this->_ArraytoSqlStr($array);
			$query ="insert into {$this->_table} set ".implode(',',$arr);
			$this->init();
			if($this->query($query,false)){
				return $this->_link->insert_id;
			}
			return false;
		}
	}
	public function update($array){
		if(!empty($array)){
			$arr = $this->_ArraytoSqlStr($array);
			$query ="update {$this->_table} set ".implode(',',$arr)." {$this->_sql['where']}";
			$this->init();
			if( $this->query($query,false)){
				return true;
			}else{
				return false;
			}
		}
	}
	public function delete(){
		$query ="delete from {$this->_table} {$this->_sql['where']}";
		$this->init();
		if( $this->query($query,false) === true){
			return true;
		}else{
			return false;
		}
		return false;
	}
	public function select(){
		$query = "SELECT {$this->_sql['fields']} FROM {$this->_table} {$this->_sql['join']} {$this->_sql['where']} {$this->_sql['groupby']} {$this->_sql['having']} {$this->_sql['orderby']} {$this->_sql['limit']}";
		$this->init();
		return $this->query($query)->fetchAll();
	}
	public function find(){
		$query = "SELECT {$this->_sql['fields']} FROM {$this->_table} {$this->_sql['join']} {$this->_sql['where']} {$this->_sql['groupby']} {$this->_sql['having']} {$this->_sql['orderby']} {$this->_sql['limit']}";
		$this->init();
		return $this->query($query)->fetch();
	}
	public function fields($fields = '*'){
		$this->_sql['fields'] = $fields;
		return $this;
	}
	public function where($sql){
		$_args = trim($sql);
		if($_args != null){
			$return = 'WHERE ';
			//$return .= ' AND ';
			$return .="({$_args})";
		}
		$this->_sql['where'] = $return;
		return $this;
	}
	public function limit($sql){
		$_args = trim($sql);
		$return = '0,1000';
		if($_args != null){
			$return = ' LIMIT ';
			$return .=$_args;
		}
		$this->_sql['limit'] = $return;
		return $this;
	}
	public function orderby($sql){
		$_args = trim($sql);
		$return = '';
		if($_args != null){
			$return = ' ORDER BY ';
			$return .=$_args;
		}
		$this->_sql['orderby'] = $return;
		return $this;
	}
	public function groupby($sql){
		$_args = trim($sql);
		$return = '';
		if($_args != null){
			$return = ' GROUP BY ';
			$return .=$_args;
		}
		$this->_sql['groupby'] = $return;
		return $this;
	}
	/*修改*/
	public function join($table,$where,$join=''){
		$_args = func_get_args();
		$return = '';
		if(is_array($_args) && !empty($_args)){
			if(!isset($_args[2])){
			$type = 'LEFT';
			}else{
				$type = $_args[2];
			}
			$return = ' ' . $type . ' JOIN ';
			$return .=' '.$_args[0].' ON (';
			$return .=' '.$_args[1] . ')';
		}
		$this->_sql['join'] = $return;
		return $this;
	}
	public function having($sql){
		$_args = trim($sql);
		$return = '';
		if($_args != null){
			$return = ' HAVING ';
			$return .=$_args;
		}
		$this->_sql['having'] = $return;
		return $this;
	}
	public function query($sql,$result=true){
		if($result !== true){
			$query = $this->_link->query($sql);
			$this->geterron();
			return $query;
		}else{
			$query = $this->_link->real_query($sql);
			$this->geterron();
			return new Db_MySQLi_Result($this->_link);
		}
	}
	public function geterron(){
		if($this->_link->errno > 0){
			throw new MysqliDbException($this->_link->error);
		}
	}
}
class Db_MySQLi_Result extends MySQLi_Result implements Db_Result
{
    public function fetch()
    {
        return $this->fetch_assoc();
    }
    public function fetchAll()
    {
        $rows = array();
        while($row = $this->fetch())
        {
            $rows[] = $row;
        }
        return $rows;
    }
}
class MysqliDbException extends DbException{}
class MysqliDbResultException extends DbException{}